import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'logger.dart';

/// 自定义缓存管理器
/// 配置更长的缓存时间和更大的缓存空间
class AppCacheManager {
  static const String key = 'matrixAppCache';

  static CacheManager? _instance;

  // 缓存统计
  static int _cacheHitCount = 0;
  static int _cacheMissCount = 0;
  static int _networkLoadCount = 0;

  /// 获取缓存管理器实例
  /// 缓存有效期：7天
  /// 最大缓存文件数：500个
  static CacheManager get instance {
    _instance ??= CacheManager(
      Config(
        key,
        stalePeriod: const Duration(days: 7), // 缓存有效期7天
        maxNrOfCacheObjects: 500, // 最多缓存500个文件
        repo: JsonCacheInfoRepository(databaseName: key),
        fileService: HttpFileService(),
      ),
    );
    return _instance!;
  }

  /// 记录缓存命中
  static void recordCacheHit(String url, String type) {
    _cacheHitCount++;
    final shortUrl = _getShortUrl(url);
    Logger.d('📦 CACHE_HIT', '[$type] 从缓存加载: $shortUrl (总命中: $_cacheHitCount)');
  }

  /// 记录缓存未命中（需要从网络加载）
  static void recordCacheMiss(String url, String type) {
    _cacheMissCount++;
    final shortUrl = _getShortUrl(url);
    Logger.d('🌐 CACHE_MISS', '[$type] 从网络加载: $shortUrl (总未命中: $_cacheMissCount)');
  }

  /// 记录网络加载完成
  static void recordNetworkLoad(String url, String type) {
    _networkLoadCount++;
    final shortUrl = _getShortUrl(url);
    Logger.d('✅ NETWORK_LOADED', '[$type] 网络加载完成并缓存: $shortUrl (总网络加载: $_networkLoadCount)');
  }

  /// 记录加载失败
  static void recordLoadError(String url, String type, dynamic error) {
    final shortUrl = _getShortUrl(url);
    Logger.e('❌ LOAD_ERROR', '[$type] 加载失败: $shortUrl, 错误: $error');
  }

  /// 获取缓存统计信息
  static String getCacheStats() {
    final total = _cacheHitCount + _cacheMissCount;
    final hitRate = total > 0 ? (_cacheHitCount / total * 100).toStringAsFixed(1) : '0.0';
    return '缓存命中: $_cacheHitCount, 未命中: $_cacheMissCount, 命中率: $hitRate%';
  }

  /// 打印缓存统计
  static void printCacheStats() {
    Logger.d('📊 CACHE_STATS', getCacheStats());
  }

  /// 重置统计
  static void resetStats() {
    _cacheHitCount = 0;
    _cacheMissCount = 0;
    _networkLoadCount = 0;
    Logger.d('🔄 CACHE_STATS', '统计已重置');
  }

  /// 获取短URL（用于日志显示）
  static String _getShortUrl(String url) {
    if (url.length <= 60) return url;
    // 显示域名和文件名
    final uri = Uri.tryParse(url);
    if (uri != null) {
      final host = uri.host;
      final path = uri.path;
      final fileName = path.split('/').last;
      if (fileName.isNotEmpty) {
        return '$host/.../$fileName';
      }
    }
    return '${url.substring(0, 30)}...${url.substring(url.length - 25)}';
  }

  /// 清除所有缓存
  static Future<void> clearCache() async {
    try {
      await instance.emptyCache();
      resetStats();
      Logger.d('🗑️ CACHE', '缓存已清除');
    } catch (e) {
      Logger.e('CACHE', '清除缓存失败: $e');
    }
  }

  /// 获取缓存大小（近似值，基于文件数量）
  static Future<int> getCacheFileCount() async {
    try {
      return 0;
    } catch (e) {
      Logger.e('CACHE', '获取缓存大小失败: $e');
      return 0;
    }
  }

  /// 从缓存中移除特定URL的文件
  static Future<void> removeFile(String url) async {
    try {
      await instance.removeFile(url);
      Logger.d('🗑️ CACHE', '已从缓存移除: ${_getShortUrl(url)}');
    } catch (e) {
      Logger.e('CACHE', '移除缓存文件失败: $e');
    }
  }

  /// 检查URL是否已缓存
  static Future<bool> isUrlCached(String url) async {
    try {
      final fileInfo = await instance.getFileFromCache(url);
      return fileInfo != null;
    } catch (e) {
      return false;
    }
  }
}

/// 缓存网络图片组件
/// 自动缓存图片到本地，页面切换时直接从缓存加载
class CachedImageWidget extends StatefulWidget {
  final String? imageUrl;
  final double? width;
  final double? height;
  final BoxFit fit;
  final BorderRadius? borderRadius;
  final Widget? placeholder;
  final Widget? errorWidget;
  final Color? placeholderColor;
  final bool useOldImageOnUrlChange;
  final String imageType; // 图片类型标识，用于日志

  const CachedImageWidget({
    super.key,
    required this.imageUrl,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.borderRadius,
    this.placeholder,
    this.errorWidget,
    this.placeholderColor,
    this.useOldImageOnUrlChange = true,
    this.imageType = '图片',
  });

  @override
  State<CachedImageWidget> createState() => _CachedImageWidgetState();
}

class _CachedImageWidgetState extends State<CachedImageWidget> {
  bool _isFromCache = false;
  bool _hasCheckedCache = false;

  @override
  void initState() {
    super.initState();
    _checkCacheStatus();
  }

  @override
  void didUpdateWidget(CachedImageWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.imageUrl != widget.imageUrl) {
      _hasCheckedCache = false;
      _checkCacheStatus();
    }
  }

  Future<void> _checkCacheStatus() async {
    if (widget.imageUrl == null || widget.imageUrl!.isEmpty) return;
    
    final isCached = await AppCacheManager.isUrlCached(widget.imageUrl!);
    if (mounted) {
      setState(() {
        _isFromCache = isCached;
        _hasCheckedCache = true;
      });
      
      if (isCached) {
        AppCacheManager.recordCacheHit(widget.imageUrl!, widget.imageType);
      } else {
        AppCacheManager.recordCacheMiss(widget.imageUrl!, widget.imageType);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // 处理空URL或无效URL
    if (widget.imageUrl == null ||
        widget.imageUrl!.isEmpty ||
        widget.imageUrl!.contains('via.placeholder.com')) {
      Logger.d('🚫 CACHED_IMAGE', '[${widget.imageType}] URL为空或无效，显示占位符');
      return _buildPlaceholder();
    }

    final Widget imageWidget = CachedNetworkImage(
      imageUrl: widget.imageUrl!,
      width: widget.width,
      height: widget.height,
      fit: widget.fit,
      cacheManager: AppCacheManager.instance,
      useOldImageOnUrlChange: widget.useOldImageOnUrlChange,
      placeholder: (context, url) {
        return widget.placeholder ?? _buildLoadingPlaceholder();
      },
      errorWidget: (context, url, error) {
        AppCacheManager.recordLoadError(url, widget.imageType, error);
        return widget.errorWidget ?? _buildErrorPlaceholder();
      },
      imageBuilder: (context, imageProvider) {
        // 图片加载成功
        if (!_isFromCache && _hasCheckedCache) {
          // 如果之前检查不在缓存，说明是从网络加载的
          AppCacheManager.recordNetworkLoad(widget.imageUrl!, widget.imageType);
        }
        return Container(
          width: widget.width,
          height: widget.height,
          decoration: BoxDecoration(
            borderRadius: widget.borderRadius,
            image: DecorationImage(
              image: imageProvider,
              fit: widget.fit,
            ),
          ),
        );
      },
      fadeInDuration: const Duration(milliseconds: 200),
      fadeOutDuration: const Duration(milliseconds: 200),
    );

    if (widget.borderRadius != null) {
      return ClipRRect(
        borderRadius: widget.borderRadius!,
        child: imageWidget,
      );
    }

    return imageWidget;
  }

  Widget _buildPlaceholder() {
    return Container(
      width: widget.width,
      height: widget.height,
      decoration: BoxDecoration(
        color: widget.placeholderColor ?? Colors.grey[200],
        borderRadius: widget.borderRadius ?? BorderRadius.circular(8),
      ),
      child: Icon(
        Icons.image,
        size: _getIconSize(),
        color: Colors.grey[400],
      ),
    );
  }

  Widget _buildLoadingPlaceholder() {
    return Container(
      width: widget.width,
      height: widget.height,
      decoration: BoxDecoration(
        color: widget.placeholderColor ?? Colors.grey[100],
        borderRadius: widget.borderRadius ?? BorderRadius.circular(8),
      ),
      child: Center(
        child: SizedBox(
          width: 24,
          height: 24,
          child: CircularProgressIndicator(
            strokeWidth: 2,
            color: Colors.grey[400],
          ),
        ),
      ),
    );
  }

  Widget _buildErrorPlaceholder() {
    return Container(
      width: widget.width,
      height: widget.height,
      decoration: BoxDecoration(
        color: widget.placeholderColor ?? Colors.grey[200],
        borderRadius: widget.borderRadius ?? BorderRadius.circular(8),
      ),
      child: Icon(
        Icons.broken_image,
        size: _getIconSize(),
        color: Colors.grey[400],
      ),
    );
  }

  double _getIconSize() {
    if (widget.width != null && widget.height != null) {
      return (widget.width! + widget.height!) / 6;
    }
    return 48;
  }
}

/// 缓存头像组件
/// 专门用于显示用户头像，支持圆形裁剪
class CachedAvatarWidget extends StatefulWidget {
  final String? avatarUrl;
  final double size;
  final Color? backgroundColor;
  final Color? iconColor;
  final Widget? placeholder;

  const CachedAvatarWidget({
    super.key,
    required this.avatarUrl,
    this.size = 40,
    this.backgroundColor,
    this.iconColor,
    this.placeholder,
  });

  @override
  State<CachedAvatarWidget> createState() => _CachedAvatarWidgetState();
}

class _CachedAvatarWidgetState extends State<CachedAvatarWidget> {
  bool _isFromCache = false;
  bool _hasCheckedCache = false;

  @override
  void initState() {
    super.initState();
    _checkCacheStatus();
  }

  @override
  void didUpdateWidget(CachedAvatarWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.avatarUrl != widget.avatarUrl) {
      _hasCheckedCache = false;
      _checkCacheStatus();
    }
  }

  Future<void> _checkCacheStatus() async {
    if (widget.avatarUrl == null || widget.avatarUrl!.isEmpty) return;
    
    final isCached = await AppCacheManager.isUrlCached(widget.avatarUrl!);
    if (mounted) {
      setState(() {
        _isFromCache = isCached;
        _hasCheckedCache = true;
      });
      
      if (isCached) {
        AppCacheManager.recordCacheHit(widget.avatarUrl!, '头像');
      } else {
        AppCacheManager.recordCacheMiss(widget.avatarUrl!, '头像');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // 处理空URL或无效URL
    if (widget.avatarUrl == null ||
        widget.avatarUrl!.isEmpty ||
        widget.avatarUrl!.contains('via.placeholder.com')) {
      Logger.d('🚫 CACHED_AVATAR', '[头像] URL为空或无效，显示占位符');
      return _buildPlaceholder();
    }

    return ClipOval(
      child: CachedNetworkImage(
        imageUrl: widget.avatarUrl!,
        width: widget.size,
        height: widget.size,
        fit: BoxFit.cover,
        cacheManager: AppCacheManager.instance,
        placeholder: (context, url) {
          return widget.placeholder ?? _buildLoadingPlaceholder();
        },
        errorWidget: (context, url, error) {
          AppCacheManager.recordLoadError(url, '头像', error);
          return _buildPlaceholder();
        },
        imageBuilder: (context, imageProvider) {
          if (!_isFromCache && _hasCheckedCache) {
            AppCacheManager.recordNetworkLoad(widget.avatarUrl!, '头像');
          }
          return Container(
            width: widget.size,
            height: widget.size,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              image: DecorationImage(
                image: imageProvider,
                fit: BoxFit.cover,
              ),
            ),
          );
        },
        fadeInDuration: const Duration(milliseconds: 150),
        fadeOutDuration: const Duration(milliseconds: 150),
      ),
    );
  }

  Widget _buildPlaceholder() {
    return Container(
      width: widget.size,
      height: widget.size,
      decoration: BoxDecoration(
        color: widget.backgroundColor ?? Colors.grey[300],
        shape: BoxShape.circle,
      ),
      child: Icon(
        Icons.person,
        size: widget.size * 0.6,
        color: widget.iconColor ?? Colors.grey[600],
      ),
    );
  }

  Widget _buildLoadingPlaceholder() {
    return Container(
      width: widget.size,
      height: widget.size,
      decoration: BoxDecoration(
        color: widget.backgroundColor ?? Colors.grey[200],
        shape: BoxShape.circle,
      ),
      child: Center(
        child: SizedBox(
          width: widget.size * 0.4,
          height: widget.size * 0.4,
          child: CircularProgressIndicator(
            strokeWidth: 2,
            color: Colors.grey[400],
          ),
        ),
      ),
    );
  }
}

/// 缓存封面图组件
/// 专门用于视频/文章封面，支持播放按钮叠加
class CachedCoverWidget extends StatelessWidget {
  final String? coverUrl;
  final double? width;
  final double? height;
  final BorderRadius? borderRadius;
  final bool showPlayButton;
  final VoidCallback? onTap;

  const CachedCoverWidget({
    super.key,
    required this.coverUrl,
    this.width,
    this.height,
    this.borderRadius,
    this.showPlayButton = false,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final Widget coverImage = CachedImageWidget(
      imageUrl: coverUrl,
      width: width,
      height: height,
      fit: BoxFit.cover,
      borderRadius: borderRadius ?? BorderRadius.circular(8),
      imageType: '封面',
    );

    Widget result = coverImage;

    // 添加播放按钮
    if (showPlayButton) {
      result = Stack(
        alignment: Alignment.center,
        children: [
          coverImage,
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.5),
              shape: BoxShape.circle,
            ),
            child: const Icon(
              Icons.play_arrow,
              color: Colors.white,
              size: 30,
            ),
          ),
        ],
      );
    }

    // 添加点击事件
    if (onTap != null) {
      result = GestureDetector(
        onTap: onTap,
        child: result,
      );
    }

    return result;
  }
}
